package com.xmtlxx.web.controller.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysDept;
import com.xmtlxx.common.core.domain.entity.SysUser;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.PropertyLogNode;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.JsonUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.oms.domain.Property;
import com.xmtlxx.oms.domain.PropertyLog;
import com.xmtlxx.oms.domain.Task;
import com.xmtlxx.oms.domain.TaskDtl;
import com.xmtlxx.oms.domain.bo.TaskBo;
import com.xmtlxx.oms.domain.bo.TaskDtlBo;
import com.xmtlxx.oms.domain.vo.PropertyVo;
import com.xmtlxx.oms.domain.vo.TaskVo;
import com.xmtlxx.oms.mapper.PropertyLogMapper;
import com.xmtlxx.oms.mapper.PropertyMapper;
import com.xmtlxx.oms.mapper.TaskDtlMapper;
import com.xmtlxx.oms.mapper.TaskMapper;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.mapper.SysDeptMapper;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.mapper.SysUserMapper;
import com.xmtlxx.system.service.ISysUserService;
import com.xmtlxx.tms.domain.Order;
import com.xmtlxx.tms.domain.vo.OrderVo;
import com.xmtlxx.tms.domain.vo.WaybillDtlVo;
import com.xmtlxx.tms.domain.vo.WaybillVo;
import com.xmtlxx.tms.mapper.OrderMapper;
import com.xmtlxx.web.controller.tms.service.IOrderService;
import com.xmtlxx.web.controller.tms.service.IWaybillDtlService;
import com.xmtlxx.web.controller.tms.service.IWaybillService;
import com.xmtlxx.web.controller.wms.service.IHandoverService;
import com.xmtlxx.wms.domain.ExWarehouse;
import com.xmtlxx.wms.domain.Handover;
import com.xmtlxx.wms.domain.HandoverDtl;
import com.xmtlxx.wms.domain.Warehouse;
import com.xmtlxx.wms.domain.bo.HandoverBo;
import com.xmtlxx.wms.domain.bo.HandoverDtlBo;
import com.xmtlxx.wms.domain.vo.*;
import com.xmtlxx.wms.mapper.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 交接信息Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HandoverServiceImpl implements IHandoverService {

    private final HandoverMapper baseMapper;

    private final HandoverDtlMapper handoverDtlMapper;

    private final SysOssMapper ossMapper;

    private final PropertyLogMapper propertyLogMapper;

    private final TaskMapper taskMapper;

    private final TaskDtlMapper taskDtlMapper;

    private final OrderMapper orderMapper;

    private final StoreMapper storeMapper;

    private final SysDeptMapper deptMapper;

    private final SysUserMapper userMapper;

    private final WarehouseMapper warehouseMapper;

    private final ExWarehouseMapper exWarehouseMapper;

    private final PropertyMapper propertyMapper;

    private final IWaybillService waybillService;

    private final IWaybillDtlService waybillDtlService;

    private final IOrderService orderService;

    private final ISysUserService userService;

    /**
     * 查询交接信息
     *
     * @param id 交接信息主键
     * @return 交接信息
     */
    @Override
    public HandoverVo queryById(String id) {
        //return baseMapper.selectVoById(id);
        return baseMapper.selectHandoverVoByID(id);
    }

    @Override
    public HandoverVo queryByObjid(HandoverBo handover) {

        return baseMapper.selectHandoverVoByObjid(handover);
    }

    /**
     * 查询交接信息列表
     *
     * @param bo 交接信息
     * @return 交接信息
     */
    @Override
    public TableDataInfo<HandoverVo> queryPageList(HandoverBo bo, PageQuery pageQuery) {
        // LambdaQueryWrapper<Handover> lqw = buildQueryWrapper(bo);
        // Page<HandoverVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<HandoverVo> result = baseMapper.selectPageHandoverList(pageQuery.build(), bo);
        if (result != null && result.getRecords() != null && result.getRecords().size() > 0) {
            for (HandoverVo vo : result.getRecords()) {
                HandoverDtlBo dtlBo = new HandoverDtlBo();
                dtlBo.setHid(vo.getId());
                dtlBo.setDelFlag("0");
                List<HandoverDtlVo> items = handoverDtlMapper.selectHandoverDtlList(dtlBo);
                items = items.stream().map(data -> {
                    HandoverDtlVo dtlVo = new HandoverDtlVo();
                    BeanUtil.copyProperties(data, dtlVo);
                    SysOssBo ossBo = new SysOssBo();
                    ossBo.setObjid(dtlVo.getId());
                    ossBo.setBuss("handoverDtl");
                    dtlVo.setOss(ossMapper.selectSysOssList(ossBo));


                    return dtlVo;
                }).collect(Collectors.toList());

                vo.setItems(items);
                vo.setTakeItems(items);
                if (StringUtils.isNotEmpty(vo.getType()) && !vo.getType().equals("0")) {
                    HandoverVo handover = baseMapper.selectVoOne(new LambdaQueryWrapper<Handover>()
                            .eq(Handover::getObjid, vo.getObjid())
                            .eq(Handover::getType, "0"));
                    if (handover != null) {
                        vo.setHandTime(handover.getHandTime());
                    }
                }

                OrderVo orderVo = orderMapper.selectVoOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, vo.getObjid()));
                if (orderVo != null) {
                    vo.setTaskNo(orderVo.getOrderNo());
                    if (vo.getOperator() != null) {
                        SysUser operUser = new SysUser();
                        operUser.setUserId(vo.getOperator());
                        vo.setOperatorName(userMapper.selectUserId(operUser).getNickName());
                    }
                    if (vo.getCounterpart() != null) {
                        SysUser countUser = new SysUser();
                        countUser.setUserId(vo.getCounterpart());
                        vo.setCounterpartName(userMapper.selectUserId(countUser).getNickName());
                    }
                    vo.setPickUpAddress(orderVo.getSendAddress());
                    vo.setArrivalAddress(orderVo.getTakeAddress());
                    vo.setArrivalTime(orderVo.getArriveTime());
                    if (orderVo.getArriveTime() == null) {
                        if (StringUtils.isNotEmpty(orderVo.getFid())) {
                            OrderVo fOrder = orderMapper.selectOrderVoByID(orderVo.getFid());
                            vo.setArrivalTime(fOrder.getArriveTime());
                        }
                    } else {
                        vo.setArrivalTime(orderVo.getArriveTime());
                    }
                    vo.setArrivaler(orderVo.getTakeContacts());
                }
                SysUser operUser = new SysUser();
                operUser.setUserId(vo.getOperator());
                SysUser operatorUser = userMapper.selectUserId(operUser);
                if (vo.getType().equals("2")) {
                    vo.setTransferDeptName(deptMapper.selectVoById(orderVo.getDeptId()).getDeptName());
                } else {
                    if (operatorUser != null) {
                        SysDept sysDept = deptMapper.selectVoById(operatorUser.getDeptId());
                        if (sysDept != null) {
                            vo.setTransferDeptName(sysDept.getDeptName());
                        }
                    }
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 申请单详情-交接信息
     *
     * @param bo
     * @return
     */
    @Override
    public List<HandoverVo> queryInfoList(HandoverBo bo) {

        Task task = taskMapper.selectById(bo.getObjid());
        if (StrUtil.isNotBlank(bo.getObjid())) {
            if (StrUtil.isNotBlank(task.getReplaceNo())) {
                TaskBo taskBo = new TaskBo();
                taskBo.setTaskNo(task.getReplaceNo());
                TaskVo taskVo = taskMapper.selectTaskVoByTaskNo(taskBo);
                bo.setObjid(taskVo.getId());
            }
        }
        List<HandoverVo> result = new ArrayList<>();
        List<HandoverVo> handoverVos = baseMapper.selectHandoverList(bo);
        if (handoverVos != null && handoverVos.size() > 0) {
            HandoverVo infoVo = new HandoverVo();
            HandoverVo enty = null;
            for (HandoverVo vo : handoverVos) {
                TaskVo taskVo = taskMapper.selectVoById(vo.getObjid());
                switch (vo.getType()) {
                    case "0":
                        if (taskVo.getType().equals("0")) {
                            infoVo.setSigns(vo.getSigns());//移送人
                            infoVo.setHandPics(vo.getHandPics());//取件人
                            infoVo.setPickUpTime(vo.getHandTime());
                        } else {
                            infoVo.setCounterpartSign(vo.getCounterpartSign());//中心受理人
                            infoVo.setCheckSign(vo.getCheckSign());//中心保管人
                            infoVo.setHandPics(vo.getHandPics());//送件人
                            infoVo.setPickUpTime(vo.getHandTime());
                        }

                        enty = vo;
                        break;
                    case "1":
                        if (taskVo.getType().equals("0")) {
                            infoVo.setCounterpartSign(vo.getCounterpartSign());//收件人
                            infoVo.setCheckSign(vo.getCheckSign());//复核人
                            infoVo.setHandTime(vo.getHandTime());
                            infoVo.setArrivalTime(vo.getHandTime());
                            infoVo.setSigns(vo.getSigns());
                        } else {
                            if (taskVo.getDelivery().equals("1")) {
                                infoVo.setCounterpartSign(vo.getCounterpartSign());//收件人
                                infoVo.setCheckSign(vo.getCheckSign());//复核人
                                infoVo.setPickUpTime(vo.getHandTime());
                            }
                            infoVo.setHandTime(vo.getHandTime());
                            infoVo.setArrivalTime(vo.getHandTime());
                            infoVo.setSigns(vo.getSigns());
                        }

                        enty = vo;
                        break;
                    case "2"://暂存
                        HandoverVo staging = new HandoverVo();
                        staging.setSigns(vo.getSigns());//移送人
                        staging.setHandPics(vo.getHandPics());//取件人
                        staging.setCounterpartSign(vo.getCounterpartSign());//暂存点
                        staging.setCheckSign(vo.getCheckSign());//暂存点

                        staging.setPickUpTime(vo.getPickUpTime());
                        staging.setArrivalTime(vo.getHandTime());
                        HandoverDtlBo dtlBo = new HandoverDtlBo();
                        dtlBo.setHid(vo.getId());
                        dtlBo.setDelFlag("0");
                        staging.setTakeItems(handoverDtlMapper.selectHandoverDtlList(dtlBo));

                        SysUser operUser = new SysUser();
                        operUser.setUserId(vo.getOperator());
                        SysUser operatorUser = userMapper.selectUserId(operUser);
                        if (operatorUser != null) {
                            SysDept sysDept = deptMapper.selectVoById(taskVo.getDeptId());
                            if (sysDept != null) {
                                //移送单位
                                staging.setTransferDeptName(sysDept.getDeptName());
                            }
                        }

                        SysUser counUser = new SysUser();
                        counUser.setUserId(vo.getOperator());
                        SysUser counterpartUser = userMapper.selectUserId(counUser);
                        if (counterpartUser != null) {
                            SysDept sysDept = deptMapper.selectVoById(counterpartUser.getDeptId());
                            if (sysDept != null) {
                                //配送单位
                                staging.setOrderDeptName(sysDept.getDeptName());
                            }
                        }

                        //订单编号
                        OrderVo orderVo = orderMapper.selectVoOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, vo.getObjid()));
                        if (orderVo != null) {
                            staging.setTaskNo(orderVo.getOrderNo());
                            //收货人
                            staging.setArrivaler(counterpartUser.getNickName());

                            staging.setOrderCreates(orderVo.getCreateTime());
                        }


                        if (taskVo != null) {
                            StoreVo storeVo = storeMapper.selectVoById(taskVo.getStoreId());
                            //收件单位
                            SysDept sysDept = deptMapper.selectVoById(storeVo.getDeptId());
                            if (sysDept != null) {
                                staging.setReceiveDeptName(sysDept.getDeptName());
                            }

                            staging.setTaskType(taskVo.getDelivery());
                        }
                        staging.setHtype("1");
                        staging.setHandTime(vo.getHandTime());
                        result.add(staging);
                        return result;
                    default:
                        return null;
                }
            }

            //查询运单里的签收人


            HandoverDtlBo dtlBo = new HandoverDtlBo();
            dtlBo.setHid(enty.getId());
            dtlBo.setDelFlag("0");
            //交接财物
            List<HandoverDtlVo> items = handoverDtlMapper.selectHandoverDtlList(dtlBo);

            items.forEach(item -> {
                PropertyVo vo = propertyMapper.selectVoOne(new LambdaQueryWrapper<Property>().eq(Property::getPno, item.getPno()));
                if (vo != null) {
                    item.setCharacter(vo.getCharacter());
                }
            });

            //单子替换只显示下单财物
            if (task != null && StrUtil.isNotBlank(task.getReplaceNo())) {

                TaskDtlBo taskDtlBo = new TaskDtlBo();
                taskDtlBo.setTaskId(task.getId());
                taskDtlBo.setDelFlag("0");
                List<TaskDtl> taskDtls = taskDtlMapper.selectTaskDtl(taskDtlBo);
                List<String> taskDtlPNos = taskDtls.stream().map(TaskDtl::getPno).collect(Collectors.toList());

                items = items.stream().filter(item -> taskDtlPNos.contains(item.getPno())).collect(Collectors.toList());
            }

            infoVo.setTakeItems(items);

//            SysUser operUser = new SysUser();
//            operUser.setUserId(enty.getOperator());
//            SysUser operatorUser = userMapper.selectUserId(operUser);
//            if(operatorUser != null){
//                SysDept sysDept = deptMapper.selectVoById(operatorUser.getDeptId());
//                if(sysDept != null){
//                    //移送单位
//                    infoVo.setTransferDeptName(sysDept.getDeptName());
//                }
//            }
            //订单编号
            OrderVo orderVo = orderMapper.selectVoOne(new LambdaQueryWrapper<Order>().eq(Order::getTaskId, enty.getObjid()));
            if (orderVo != null) {
                infoVo.setTaskNo(orderVo.getOrderNo());
                //收货人
                infoVo.setArrivaler(orderVo.getTakeContacts());

                infoVo.setOrderCreates(orderVo.getCreateTime());

                infoVo.setSigneeName(orderVo.getSigneeName());
            }
            WarehouseVo warehouseVo = warehouseMapper.selectVoOne(new LambdaQueryWrapper<Warehouse>().eq(Warehouse::getTaskId, enty.getObjid()));
            if (warehouseVo != null) {
                infoVo.setTaskNo(warehouseVo.getWno());
                //收货人
                infoVo.setArrivaler(warehouseVo.getName());
            }

            ExWarehouseVo exWarehouseVo = exWarehouseMapper.selectVoOne(new LambdaQueryWrapper<ExWarehouse>().eq(ExWarehouse::getTaskId, enty.getObjid()));

            if (exWarehouseVo != null) {
                infoVo.setTaskNo(exWarehouseVo.getExno());
                //收货人
                infoVo.setArrivaler(exWarehouseVo.getContacts());
            }
            SysUser counUser = new SysUser();
            if (enty.getType().equals("0")) {
                counUser.setUserId(enty.getCounterpart());
            } else {
                counUser.setUserId(enty.getOperator());
            }
            SysUser counterpartUser = userMapper.selectUserId(counUser);
            if (counterpartUser != null) {
                SysDept sysDept = deptMapper.selectVoById(counterpartUser.getDeptId());
                if (sysDept != null) {
                    //配送单位
                    infoVo.setOrderDeptName(sysDept.getDeptName());
                }
            }
            TaskVo taskVo = taskMapper.selectVoById(enty.getObjid());
            if (taskVo != null) {
                StoreVo storeVo = storeMapper.selectVoById(taskVo.getStoreId());
                //收件单位
                SysDept sysDept = deptMapper.selectVoById(storeVo.getDeptId());
                if (sysDept != null) {
                    infoVo.setReceiveDeptName(sysDept.getDeptName());
                }

                SysDept dept = deptMapper.selectVoById(taskVo.getDeptId());

                infoVo.setTransferDeptName(dept.getDeptName());

                infoVo.setTaskType(taskVo.getDelivery());
            }
            infoVo.setHtype("0");
            result.add(infoVo);
        }


        return result;
    }

    /**
     * 查询交接信息列表
     *
     * @param bo 交接信息
     * @return 交接信息
     */
    @Override
    public List<HandoverVo> queryList(HandoverBo bo) {
        // LambdaQueryWrapper<Handover> lqw = buildQueryWrapper(bo);
        // return baseMapper.selectVoList(lqw);
        return baseMapper.selectHandoverList(bo);
    }

    private LambdaQueryWrapper<Handover> buildQueryWrapper(HandoverBo bo) {

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Handover> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getOperator() != null, Handover::getOperator, bo.getOperator());
        lqw.between(params.get("beginHandTime") != null && params.get("endHandTime") != null,
                Handover::getHandTime, params.get("beginHandTime"), params.get("endHandTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Handover::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Handover::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增交接信息
     *
     * @param bo 交接信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HandoverVo insertByBo(HandoverBo bo) {

        HandoverVo vo = new HandoverVo();
        Handover add = BeanUtil.toBean(bo, Handover.class);
        validEntityBeforeSave(add);

        String[] ignoreProperties = {"ossId", "createBy", "createTime", "updateBy", "updateTime"};

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setStatus("0");
        add.setDelFlag("0");
        add.setHandTime(new Date());

        /**
         * 物品交接运输单
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            bo.getOss().stream().forEach(item -> {
                item.setObjid(bo.getTaskId());
                item.setBuss("handoverDtl");
                ossMapper.updateById(item);

                add.setSignsFile(item.getFileName());
            });
        }


        //移送人签名透明图片
        SysOss signOss = ossMapper.selectById(bo.getSignOssId());
        if (signOss != null) {
            signOss.setBuss("signs");
            signOss.setObjid(add.getId());
            ossMapper.updateById(signOss);
        }

        //中心保管员签名透明图片
        SysOss counterpartOss = ossMapper.selectById(bo.getCtpOssId());
        if (counterpartOss != null) {
            counterpartOss.setBuss("counterpart");
            counterpartOss.setObjid(add.getId());
            ossMapper.updateById(counterpartOss);
        }

        //复核人签名透明图片
        SysOss checkOss = ossMapper.selectById(bo.getCheckOssId());
        if (checkOss != null) {
            checkOss.setBuss("check");
            checkOss.setObjid(add.getId());
            ossMapper.updateById(checkOss);
        }

        //取货人签名透明图片
        SysOss pickUpOss = ossMapper.selectById(bo.getPuOssId());
        if (pickUpOss != null) {
            pickUpOss.setBuss("pickUp");
            pickUpOss.setObjid(add.getId());
            ossMapper.updateById(pickUpOss);
        }


        //交接清单名称
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            for (HandoverDtlVo dtl : bo.getItems()) {
                dtl.setId(IdUtil.simpleUUID());
                dtl.setHid(add.getId());
                dtl.setDelFlag("0");
                /**
                 * 批量签收时定义查询
                 */
                dtl.setSignStatus("0");

                //交接清单附件
                if (dtl.getOss() != null && dtl.getOss().size() > 0) {
                    for (SysOss oss : dtl.getOss()) {
//                       if(StringUtils.isNotEmpty(dtl.getBoxId())){
//                           SysOss copyOss = new SysOss();
//                           BeanUtil.copyProperties(oss,copyOss,"ossId");
//                           copyOss.setObjid(dtl.getId());
//                           copyOss.setBuss("handoverDtl");
//                           ossMapper.insertOrUpdate(copyOss);
//                       }else {
//                           oss.setObjid(dtl.getId());
//                           oss.setBuss("handoverDtl");
//                           ossMapper.insertOrUpdate(oss);
//                       }
                        if (oss.getBuss().equals("facade")) {
                            SysOss newOss = new SysOss();
                            BeanUtil.copyProperties(oss, newOss, ignoreProperties);
                            newOss.setObjid(dtl.getId());
                            newOss.setBuss("handoverDtl");
                            ossMapper.insert(newOss);
                        } else {
                            oss.setObjid(dtl.getId());
                            oss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(oss);
                        }
                    }
                }
                HandoverDtl handoverDtl = new HandoverDtl();
                BeanUtil.copyProperties(dtl, handoverDtl);
                handoverDtlMapper.insertOrUpdate(handoverDtl);

//                Long deptId = null;
//                String content = "";
//                TaskVo taskVo = taskMapper.selectTaskVoByID(add.getObjid());
//                if(StringUtils.isNotEmpty(bo.getAction()) && ObjectUtil.isNotNull(taskVo)){
//                    if(bo.getAction().equals("1") || bo.getAction().equals("2")){
//                        content = "新增收件交接：(物品编号："+dtl.getPno()+"，物品名称："+dtl.getName()+"，交接说明："+(StringUtils.isNotEmpty(add.getMemo())?add.getMemo():"")+")";
//                        saveLog(dtl,taskVo.getStoreId(),add.getId(),dtl.getDeptId(),content);
//                    }
//                }
            }
        }

        boolean flag = baseMapper.insert(add) > 0;

        if (flag) {
            bo.setId(add.getId());
        }

        BeanUtil.copyProperties(add, vo);
        HandoverDtlBo dtlBo = new HandoverDtlBo();
        dtlBo.setHid(vo.getId());
        dtlBo.setDelFlag("0");
        List<HandoverDtlVo> dtlVos = handoverDtlMapper.selectHandoverDtlList(dtlBo);
        if (dtlVos != null && dtlVos.size() > 0) {
            dtlVos.stream().forEach(item -> {
                SysOssBo ossBo = new SysOssBo();
                ossBo.setObjid(item.getId());
                ossBo.setBuss("handoverDtl");
                item.setOss(ossMapper.selectSysOssList(ossBo));
            });
        }
        vo.setItems(dtlVos);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertWithAllByBo(List<HandoverBo> bos) {

        boolean flag = false;
        List<Handover> adds = bos.stream().map(item -> {
            Handover add = BeanUtil.toBean(item, Handover.class);
            List<HandoverDtl> dtls = new ArrayList<>();
            validEntityBeforeSave(add);
            add.setId(IdUtil.simpleUUID());
            add.setStatus("1");
            add.setDelFlag("0");
            add.setHandTime(new Date());

            //移送人签名透明图片
            SysOss signOss = ossMapper.selectById(item.getSignOssId());
            if (signOss != null) {
                signOss.setBuss("signs");
                signOss.setObjid(add.getId());
                ossMapper.updateById(signOss);
            }

            //中心保管员签名透明图片
            SysOss counterpartOss = ossMapper.selectById(item.getCtpOssId());
            if (counterpartOss != null) {
                counterpartOss.setBuss("counterpart");
                counterpartOss.setObjid(add.getId());
                ossMapper.updateById(counterpartOss);
            }

            //复核人签名透明图片
            SysOss checkOss = ossMapper.selectById(item.getCheckOssId());
            if (checkOss != null) {
                checkOss.setBuss("check");
                checkOss.setObjid(add.getId());
                ossMapper.updateById(checkOss);
            }

            //取货人签名透明图片
            SysOss pickUpOss = ossMapper.selectById(item.getPuOssId());
            if (pickUpOss != null) {
                pickUpOss.setBuss("pickUp");
                pickUpOss.setObjid(add.getId());
                ossMapper.updateById(pickUpOss);
            }

            //交接清单名称
            dtls = item.getItems().stream().map(dtlVo -> {
                HandoverDtl dtl = new HandoverDtl();
                BeanUtil.copyProperties(dtlVo, dtl);
                dtl.setId(IdUtil.simpleUUID());
                dtl.setHid(add.getId());
                dtl.setDelFlag("0");
                //交接清单附件
                if (dtlVo.getOss() != null && dtlVo.getOss().size() > 0) {
                    for (SysOss oss : dtlVo.getOss()) {
                        if (StringUtils.isNotEmpty(dtl.getBoxId())) {
                            SysOss copyOss = new SysOss();
                            BeanUtil.copyProperties(oss, copyOss, "ossId");
                            copyOss.setObjid(dtl.getId());
                            copyOss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(copyOss);
                        } else {
                            oss.setObjid(dtl.getId());
                            oss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(oss);
                        }
                    }
                }
                return dtl;
            }).collect(Collectors.toList());
            handoverDtlMapper.insertBatch(dtls);
            return add;
        }).collect(Collectors.toList());

        flag = baseMapper.insertBatch(adds);

        return flag;
    }

    /**
     * 修改交接信息
     *
     * @param bo 交接信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HandoverBo bo) {

        Handover update = BeanUtil.toBean(bo, Handover.class);
        validEntityBeforeSave(update);

        update.setStatus("1");//已交接
        update.setSignsStatus("1");//交接状态:0-未交接 1-已交接
        update.setHandTime(new Date());//更新为提交后的时间

        /**
         * 物品交接运输单
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            bo.getOss().stream().forEach(item -> {
                item.setObjid(bo.getObjid());
                item.setBuss("handoverDtl");
                ossMapper.updateById(item);

                update.setSignsFile(item.getFileName());
            });
        }

        //交接清单名称
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            List<HandoverDtl> dtls = bo.getItems().stream().map(item -> {
                HandoverDtl dtl = new HandoverDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setHid(update.getId());
                if (update.getType().equals("1")) {
                    dtl.setSignStatus("1");
                }

                //交接清单附件
                if (item.getOss() != null && item.getOss().size() > 0) {
                    for (SysOss oss : item.getOss()) {
                        if (StringUtils.isNotEmpty(dtl.getBoxId())) {
                            SysOss copyOss = new SysOss();
                            BeanUtil.copyProperties(oss, copyOss, "ossId");
                            copyOss.setObjid(dtl.getId());
                            copyOss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(copyOss);
                        } else {
                            oss.setObjid(dtl.getId());
                            oss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(oss);
                        }
                    }
                }

                return dtl;
            }).collect(Collectors.toList());
            handoverDtlMapper.updateBatchById(dtls);
        }

        //移送人签名透明图片
        SysOss signOss = ossMapper.selectById(bo.getSignOssId());
        if (signOss != null) {
            signOss.setBuss("signs");
            signOss.setObjid(update.getId());
            ossMapper.updateById(signOss);
        }

        //中心保管员签名透明图片
        SysOss counterpartOss = ossMapper.selectById(bo.getCtpOssId());
        if (counterpartOss != null) {
            counterpartOss.setBuss("counterpart");
            counterpartOss.setObjid(update.getId());
            ossMapper.updateById(counterpartOss);
        }

        //复核人签名透明图片
        SysOss checkOss = ossMapper.selectById(bo.getCheckOssId());
        if (checkOss != null) {
            checkOss.setBuss("check");
            checkOss.setObjid(update.getId());
            ossMapper.updateById(checkOss);
        }

        //取货人签名透明图片
        SysOss pickUpOss = ossMapper.selectById(bo.getPuOssId());
        if (pickUpOss != null) {
            pickUpOss.setBuss("pickUp");
            pickUpOss.setObjid(update.getId());
            ossMapper.updateById(pickUpOss);
        }
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HandoverVo updateByIdBo(HandoverBo bo) {

        HandoverVo vo = new HandoverVo();
        Handover update = BeanUtil.toBean(bo, Handover.class);
        validEntityBeforeSave(update);

        update.setStatus("1");//已交接
        update.setSignsStatus("1");//交接状态:0-未交接 1-已交接
        update.setHandTime(new Date());//更新为提交后的时间

        /**
         * 物品交接运输单
         */
        if (bo.getOss() != null && bo.getOss().size() > 0) {
            bo.getOss().stream().forEach(item -> {
                item.setObjid(bo.getObjid());
                item.setBuss("handoverDtl");
                ossMapper.updateById(item);

                update.setSignsFile(item.getFileName());
            });
        }

        //交接清单名称
        if (bo.getItems() != null && bo.getItems().size() > 0) {
            List<HandoverDtl> dtls = bo.getItems().stream().map(item -> {
                HandoverDtl dtl = new HandoverDtl();
                BeanUtil.copyProperties(item, dtl);
                dtl.setHid(update.getId());
                if (update.getType().equals("1")) {
                    dtl.setSignStatus("1");
                }

                //交接清单附件
                if (item.getOss() != null && item.getOss().size() > 0) {
                    for (SysOss oss : item.getOss()) {
                        if (StringUtils.isNotEmpty(dtl.getBoxId())) {
                            SysOss copyOss = new SysOss();
                            BeanUtil.copyProperties(oss, copyOss, "ossId");
                            copyOss.setObjid(dtl.getId());
                            copyOss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(copyOss);
                        } else {
                            oss.setObjid(dtl.getId());
                            oss.setBuss("handoverDtl");
                            ossMapper.insertOrUpdate(oss);
                        }
                    }
                }

                return dtl;
            }).collect(Collectors.toList());
            handoverDtlMapper.updateBatchById(dtls);
        }

        //移送人签名透明图片
        SysOss signOss = ossMapper.selectById(bo.getSignOssId());
        if (signOss != null) {
            signOss.setBuss("signs");
            signOss.setObjid(update.getId());
            ossMapper.updateById(signOss);
        }

        //中心保管员签名透明图片
        SysOss counterpartOss = ossMapper.selectById(bo.getCtpOssId());
        if (counterpartOss != null) {
            counterpartOss.setBuss("counterpart");
            counterpartOss.setObjid(update.getId());
            ossMapper.updateById(counterpartOss);
        }

        //复核人签名透明图片
        SysOss checkOss = ossMapper.selectById(bo.getCheckOssId());
        if (checkOss != null) {
            checkOss.setBuss("check");
            checkOss.setObjid(update.getId());
            ossMapper.updateById(checkOss);
        }

        //取货人签名透明图片
        SysOss pickUpOss = ossMapper.selectById(bo.getPuOssId());
        if (pickUpOss != null) {
            pickUpOss.setBuss("pickUp");
            pickUpOss.setObjid(update.getId());
            ossMapper.updateById(pickUpOss);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            BeanUtil.copyProperties(update, vo);
        }
        return vo;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Handover entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除交接信息
     *
     * @param ids 需要删除的交接信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<HandoverVo> queryListByWaybill(HandoverVo vo) {

        List<HandoverVo> handoverVos = new ArrayList<>();
        if (vo.getVos() != null && vo.getVos().size() > 0) {
            /**
             * 分组
             */
            Map<String, List<WaybillDtlVo>> groupMap = vo.getVos().stream().collect(Collectors.groupingBy(v -> v.getWaybillId()));
            groupMap.forEach((key, values) -> {
                String waybillId = key;

                List<WaybillDtlVo> dtlVos = new ArrayList<>();

                HandoverVo retunVo = new HandoverVo();
                List<HandoverDtlVo> dtls = new ArrayList<>();

                WaybillVo waybillVo = waybillService.queryById(waybillId);

                List<String> ids = values.stream().map(item -> {
                    return item.getId();
                }).collect(Collectors.toList());

                /**
                 * 查询当前运单未签收明细
                 */
                List<WaybillDtlVo> notSigns = waybillDtlService.queryWaybillVos(ids, waybillId);
                dtlVos.addAll(values);
                if (notSigns != null && notSigns.size() > 0) {
                    dtlVos.addAll(notSigns);
                }

                dtls = dtlVos.stream().map(item -> {
                    HandoverDtlVo dtl = new HandoverDtlVo();
                    BeanUtil.copyProperties(item, dtl, "id");
                    if (dtl.getOss() == null) {
                        dtl.setOss(new ArrayList<>());
                    }
                    return dtl;
                }).collect(Collectors.toList());

                OrderVo orderVo = orderService.queryById(waybillVo.getOrderId());

                if (StringUtils.isNotEmpty(orderVo.getTaskId())) {
                    HandoverBo bo = new HandoverBo();
                    bo.setObjid(orderVo.getTaskId());
                    bo.setType("0");
                    HandoverVo pickHandover = baseMapper.selectHandoverVoByObjid(bo);
                    if (pickHandover != null) {
                        retunVo.setSigns(pickHandover.getSigns());//移送人签名
                        retunVo.setHandPics(pickHandover.getHandPics());//取货人签名
                    }
                    retunVo.setTaskId(orderVo.getTaskId());
                }
                retunVo.setItems(dtls);
                retunVo.setType("1");//交接类型 0-取件 1-签收 2-暂存

                switch (orderVo.getType()) {//0-入库 1-出库 2-处置 3-调用
                    case "0":
                        //交货人
                        retunVo.setOperator(orderVo.getDispatchId());
                        retunVo.setOperatorName(userService.selectUserById(orderVo.getDispatchId()).getNickName());
                        //接货人
                        retunVo.setCounterpart(LoginHelper.getUserId());
                        retunVo.setCounterpartName(LoginHelper.getNickname());
                        break;
                    case "4"://暂存
                        //交货人
                        retunVo.setOperator(orderVo.getDispatchId());
                        retunVo.setOperatorName(userService.selectUserById(orderVo.getDispatchId()).getNickName());
                        //接货人
                        retunVo.setCounterpart(LoginHelper.getUserId());
                        retunVo.setCounterpartName(LoginHelper.getNickname());
                        break;
                    default:
                        //交货人
                        retunVo.setCounterpart(orderVo.getPickupId());
                        retunVo.setCounterpartName(userService.selectUserById(orderVo.getPickupId()).getNickName());
                        //接货人
                        retunVo.setOperator(LoginHelper.getUserId());
                        retunVo.setOperatorName(LoginHelper.getNickname());
                        break;
                }

                retunVo.setArrivalTime(orderVo.getArriveTime());
                retunVo.setTel(orderVo.getSendTel());

                retunVo.setObjid(StringUtils.isNotEmpty(orderVo.getTaskId()) ? orderVo.getTaskId() : orderVo.getId());

                retunVo.setItems(dtls);
                retunVo.setOss(new ArrayList<>());
                retunVo.setSignsStatus("0");

                if (ObjectUtil.isNotNull(orderVo)) {
                    retunVo.setTransferDeptName(orderVo.getDeptName());
                    retunVo.setTaskNo(orderVo.getOrderNo());
                    retunVo.setArrivaler(orderVo.getTakeContacts());
                    retunVo.setPickUpAddress(orderVo.getSendAddress());
                    retunVo.setArrivalAddress(orderVo.getTakeAddress());
                }

                handoverVos.add(retunVo);
            });
        }


        return handoverVos;
    }

    //财物日志添加
    private void saveLog(HandoverDtlVo dtl, String storeId, String objid, Long deptId, String content, List<SysOss> osses) {

        PropertyLog propertyLog = new PropertyLog();

        BeanUtil.copyProperties(dtl, propertyLog, "id");
        propertyLog.setId(IdUtil.simpleUUID());
        propertyLog.setObjid(objid);
        propertyLog.setDeptId(deptId);
        propertyLog.setLogTime(new Date());
        propertyLog.setStoreId(storeId);
        propertyLog.setLogType("5");//0-移交登记 1-入库 2-出库 3-调用 4-处置 5-交接 6-上架 7-挑拣
        propertyLog.setContent(content);
        propertyLog.setReceiveDept(LoginHelper.getDeptId());
        propertyLog.setUserId(LoginHelper.getUserId());
        propertyLog.setOperator(LoginHelper.getNickname());
        propertyLog.setInfo(JsonUtils.toJsonString(dtl));
        propertyLog.setDelFlag("0");
        SysDept dept = deptMapper.selectById(LoginHelper.getDeptId());
        propertyLog.setNode(PropertyLogNode.getNodeCodeByBuss(dept.getLevel(), "5"));
        propertyLogMapper.insert(propertyLog);
        if (osses != null && osses.size() > 0) {
            for (SysOss oss : osses) {
                SysOss copyOss = new SysOss();
                BeanUtil.copyProperties(oss, copyOss, "ossId");
                copyOss.setObjid(propertyLog.getId());
                copyOss.setBuss("propertyLog");
                ossMapper.insert(copyOss);
            }
        }
    }

}
